package com.yaorange.api;

import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysDictData;
import com.yaorange.common.utils.StringUtils;
import com.yaorange.nongjt.service.impl.NjtCommonService;
import com.yaorange.system.service.ISysDictDataService;
import com.yaorange.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(value = "通用接口", tags = "通用接口")
@RestController
@RequestMapping("/api/common")
public class CommonAPI {
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private NjtCommonService commonService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 根据字典类型查询字典数据信息
     */
    @ApiOperation(value = "根据字典类型查询字典列表", notes = "根据字典类型查询字典列表")
    @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, dataType = "String")
    @GetMapping(value = "/queryDictType")
    public AjaxResult queryDictType(@RequestParam("dictType") String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            return AjaxResult.error("查询失败");
        }
        return AjaxResult.success(data);
    }

    /**
     * 根据字典类型和字典值 获取字典键值
     *
     * @param dictType 字典类型
     * @param dictValue 字典值
     * @return {@link AjaxResult }
     */
    @GetMapping("/queryDictLabelByValue")
    public AjaxResult queryDictLabelByValue(String dictType, String dictValue){
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dictType);
        sysDictData.setDictValue(dictValue);
        List<SysDictData> dictData = sysDictDataService.selectDictDataList(sysDictData);
        return AjaxResult.success(dictData.get(0).getDictLabel());
    }

    /**
     * 文件上传
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public AjaxResult uploadFile(HttpServletRequest request) {
        // 文件上传目录
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        String url = commonService.uploadFile(file, bizPath);
        if (StringUtils.isBlank(url)) {
            return AjaxResult.error("上传失败");
        }
        return AjaxResult.success(url);
    }
}
